
package bsc.war.form;

import bsc.ejb.entity.Person;
import bsc.ejb.entity.ScoreDomain;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.service.BSCUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author memozac
 */
public class Login extends AbstractController {

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        String uri = request.getParameter("uri");
        try {
            Map<String,Object> params = new HashMap<String, Object>();
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");

            String username = request.getParameter("username");
            String password = request.getParameter("password");
            Person person = delegate.findPerson(username, password);

            if(person == null){
               request.setAttribute("error", "nouser");
               //the .replaceAll("&", "%26") used to scape the ampersand(&) of the uri to redirect with params
               if(uri != null) request.setAttribute("uri", uri.replaceAll("&", "%26"));
               return new ModelAndView("../index");
            }

            List<ScoreDomain> scoreDomains = BSCUtils.getAllPersonScoreDomains(delegate, person);

            if (scoreDomains.isEmpty()) return new ModelAndView("../index");

            BSCUtils.setSessionContent(request, delegate, person);

            ScoreDomain scoreDomain = scoreDomains.get(0);
            if(uri != null) params.put("uri", uri.replaceAll("&", "%26"));
            params.put("scoreDomain", scoreDomain.getIdScoreDomain().toString());

            return new ModelAndView(new RedirectView("userDomain.do"),params);
            
        } catch (Exception e) { logger.error("Catched exception",e); e.printStackTrace(); }

        return new ModelAndView("../index");
    }
}